#include <QApplication>
#include <QMainWindow>
#include <QTextEdit>
#include <QPushButton>
#include <QVBoxLayout>
#include <QHBoxLayout>
#include <QLabel>
#include <QSpinBox>
#include <QCheckBox>
#include <QRandomGenerator>
#include <QTextStream>
#include <QFile>
#include <QMessageBox>
#include <QFileDialog>
#include <QCheckBox>
#include <QSpinBox>
#include<QHash>
class PoetryGenerator : public QMainWindow {
    Q_OBJECT
public:
    PoetryGenerator(QWidget *parent = nullptr) : QMainWindow(parent) {
        setupUI();
        loadDefaultWordBank();





    }
    void showHelpInfo() {
        QString helpText =
            "词库文件格式要求：\n\n"
            "1. 使用UTF-8编码的文本文件\n"
            "2. 包含以下必需章节：\n"
            "   [nouns]      - 名词列表\n"
            "   [verbs]      - 动词列表\n"
            "   [adjectives] - 形容词列表\n"
            "   [adverbs]    - 副词列表\n\n"
            "3. 可选章节：\n"
            "   [rhymes]     - 押韵模式韵脚\n\n"
            "4. 每行一个词语，示例：\n"
            "--------------------------------\n"
            "[nouns]\n"
            "水滴\n"
            "二向箔\n"
            "\n"
            "[verbs]\n"
            "降维\n"
            "广播\n"
            "注意：章节间一定要有空格";

        QMessageBox::information(this,
                                 "导入说明",
                                 helpText,
                                 QMessageBox::Ok);
    }


private:
    QHash<QString, QString> rhymeMap = {
        {"a", "啊阿吖"},
        {"an", "安案暗"},
        {"ang", "昂盎"},
        {"ao", "奥熬傲"},
        // 继续添加其他韵母...
    };
    void setupUI() {
        QPushButton *importBtn = new QPushButton("导入词库");  // 界面组件
        QPushButton *helpBtn = new QPushButton("导入前须知");  // 界面组件
        connect(importBtn, &QPushButton::clicked, this, &PoetryGenerator::importWordBank);
        QWidget *centralWidget = new QWidget(this);
        QVBoxLayout *mainLayout = new QVBoxLayout(centralWidget);

        QHBoxLayout *controlLayout = new QHBoxLayout();
        QLabel *label = new QLabel("诗歌行数:");
        spinBox = new QSpinBox;
        spinBox->setRange(4, 100);
        spinBox->setValue(8);

        rhymeCheck = new QCheckBox("启用押韵");
        generateBtn = new QPushButton("生成诗歌");


        controlLayout->addWidget(label);
        controlLayout->addWidget(spinBox);
        controlLayout->addWidget(rhymeCheck);
        controlLayout->addWidget(generateBtn);
        controlLayout->addWidget(importBtn);
        controlLayout->addWidget(helpBtn);

        outputArea = new QTextEdit;
        outputArea->setReadOnly(true);

        mainLayout->addLayout(controlLayout);
        mainLayout->addWidget(outputArea);
        centralWidget->setLayout(mainLayout);
        setCentralWidget(centralWidget);

        connect(generateBtn, &QPushButton::clicked, this, &PoetryGenerator::generatePoetry);

        connect(helpBtn, &QPushButton::clicked, this, &PoetryGenerator::showHelpInfo);
    }

    void loadDefaultWordBank() {
        // 内置默认词库
        nouns = {"时间", "宇宙", "墓碑", "量子", "飞船", "文明", "月光", "维度"};
        verbs = {"凝固", "撕裂", "歌唱", "折叠", "坠落", "闪烁", "湮灭"};
        adjectives = {"透明的", "螺旋的", "熵增的", "递归的", "坍缩的", "量子化的"};
        adverbs = {"寂静地", "悖论般地", "在事件视界", "以光速"};
        rhymes = {"a", "o", "e", "an", "ei"};
    }
    void initRhymeBank() {
        rhymes = {"a", "o", "e", "an", "ei"}; // 简化韵母
    }

private slots:
    void generatePoetry() {
        outputArea->clear();
        QStringList poem;
        QString currentRhyme;

        if(rhymeCheck->isChecked()) {
            currentRhyme = rhymes[QRandomGenerator::global()->bounded(rhymes.size())];
        }

        for(int i=0; i<spinBox->value(); ++i) {
            QString line = generateLine(i, currentRhyme);
            poem << line;
        }

        outputArea->setText(poem.join("\n"));
    }
    void importWordBank() {
        QString fileName = QFileDialog::getOpenFileName(
            this, "选择词库文件", "", "词库文件 (*.txt)");

        if (fileName.isEmpty()) return;

        // 使用临时变量存储新词库
        QStringList newNouns, newVerbs, newAdj, newAdv, newRhymes;
        QString currentSection;

        QFile file(fileName);
        if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) {
            showError("无法打开文件");
            return;
        }

        QTextStream in(&file);


        while (!in.atEnd()) {
            QString line = in.readLine().trimmed();
            if (line.startsWith("#") || line.isEmpty()) continue;

            // 检测章节标签
            if (line.startsWith("[")) {
                currentSection = line.toLower();
                continue;
            }

            // 分配到对应词库
            if (currentSection == "[nouns]") {
                newNouns << line;
            } else if (currentSection == "[verbs]") {
                newVerbs << line;
            } else if (currentSection == "[adjectives]") {
                newAdj << line;
            } else if (currentSection == "[adverbs]") {
                newAdv << line;
            } else if (currentSection == "[rhymes]") {
                newRhymes << line;
            }
        }
        file.close();

        // 词库完整性校验
        if (newNouns.isEmpty() || newVerbs.isEmpty() ||
            newAdj.isEmpty() || newAdv.isEmpty()) {
            showError("词库文件不完整，必须包含[nouns]、[verbs]、[adjectives]、[adverbs]章节");
            return;
        }

        // 原子化更新词库
        nouns = newNouns;
        verbs = newVerbs;
        adjectives = newAdj;
        adverbs = newAdv;
        rhymes = newRhymes.isEmpty() ? rhymes : newRhymes;

        QMessageBox::information(this, "成功",
                                 QString("词库加载成功！\n名词:%1 动词:%2\n形容词:%3 副词:%4")
                                     .arg(nouns.size()).arg(verbs.size())
                                     .arg(adjectives.size()).arg(adverbs.size()));
    }

    void showError(const QString& message) {
        QMessageBox::warning(this, "格式错误",
                             QString("词库导入失败：%1\n请确保文件格式符合要求：\n"
                                     "1. 使用UTF-8编码\n"
                                     "2. 包含[nouns]、[verbs]等章节\n"
                                     "3. 每行一个词语").arg(message));
    }


private:
    QString generateLine(int lineNum, QString rhyme) {
        // 语法模板
        QVector<QString> patterns = {
            "[形容词][名词][动词][名词]",
            "[副词][动词][名词]",
            "[名词]在[动词]",
            "[形容词][名词]的[名词]"
        };

        QString pattern = patterns[QRandomGenerator::global()->bounded(patterns.size())];

        return pattern.replace("[形容词]", randomWord(adjectives))
            .replace("[名词]", randomWord(nouns))
            .replace("[动词]", randomWord(verbs))
            .replace("[副词]", randomWord(adverbs))
            .append(handleRhyme(lineNum, rhyme));
    }

    QString randomWord(const QStringList &wordList) {
        return wordList[QRandomGenerator::global()->bounded(wordList.size())];
    }

    QString handleRhyme(int lineNum, QString rhyme) {
        if(!rhyme.isEmpty() && (lineNum+1)%4 == 0) { // 每四行押韵
            return " (" + rhyme + ")"; // 此处应实现真正的押韵检测
        }
        return "";
    }

    // UI组件
    QSpinBox *spinBox;
    QCheckBox *rhymeCheck;
    QPushButton *generateBtn;
    QTextEdit *outputArea;

    // 词库
    QStringList nouns;
    QStringList verbs;
    QStringList adjectives;
    QStringList adverbs;
    QStringList rhymes;
};

int main(int argc, char *argv[]) {
    QApplication a(argc, argv);
    PoetryGenerator w;
    w.resize(600, 400);
    w.show();
    return a.exec();
}

